<template>
  <div class="login-wrap">
    <div class="ms-login">
      <div class="ms-title">{{ siteName }}后台管理系统</div>
      <el-form :model="param" :rules="rules" ref="login" label-width="0px" class="ms-content">
        <el-form-item prop="username">
          <el-input v-model="param.username" placeholder="username">
            <template #prepend>
              <el-button icon="el-icon-user"></el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" placeholder="password" v-model="param.password"
                    @keyup.enter="submitForm()">
            <template #prepend>
              <el-button icon="el-icon-lock"></el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-radio-group v-model="role">
            <el-radio label="doctor">医生/管理员</el-radio>
            <el-radio label="patient">患者</el-radio>
          </el-radio-group>
        </el-form-item>
        <div class="login-btn">
          <el-button type="primary" @click="submitForm()">登录</el-button>
        </div>
        <div class="flex-row justify-end align-center">
          <span class="text-light font14">没有账号？</span>
          <el-button type="text" @click="toggleRegModal(true)">注册用户</el-button>
        </div>
        <!--<p class="login-tips">Tips : 用户名和密码随便填。</p>-->
      </el-form>
    </div>


    <!--注册弹框 start-->
    <el-dialog
        v-model="regData.show"
        width="600px">
      <el-form
          ref="formRefName"
          :rules="regRules"
          :model="regData.data"
          label-width="80px">
        <el-form-item label="角色">
          <el-radio-group v-model="regData.data.role">
            <el-radio label="doctor">医生</el-radio>
            <el-radio label="patient">患者</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input maxlength="20" v-model="regData.data.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input :maxlength="11" v-model="regData.data.phone" placeholder="手机号"></el-input>
        </el-form-item>
        <el-form-item label="部门" v-if="regData.data.role==='doctor'">
          <el-input maxlength="20" v-model="regData.data.department" placeholder="部门"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="identityNumber">
          <el-input maxlength="18" v-model="regData.data.identityNumber" placeholder="身份证号"></el-input>
        </el-form-item>
        <el-form-item label="登录密码">
          <el-input type="password" v-model="regData.data.password" placeholder="登录密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input type="password" v-model="regData.data.rePassword" placeholder="确认密码"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="toggleRegModal(false)">取消</el-button>
          <el-button size="small" type="primary" @click="onRegister()">注册</el-button>
        </div>
      </template>
    </el-dialog>
    <!--注册弹框 end-->
  </div>
</template>

<script>
import {ref, reactive, toRaw} from "vue";
import {useStore} from "vuex";
import {RoleTypes, useUserLogin} from "../hooks/user/useUserLogin";
import Config from "../config/Config";
import {deepClone, isCard, isTrue} from "../utils/helpers";
import Toast from "../utils/Toast";
import Patient from "../api/modules/Patient";
import Doctor from "../api/modules/Doctor";
import {useRoute} from "vue-router";

export default {
  data() {
    return {
      siteName: Config.siteName,
      // 表单路由验证规则 参考： https://element-plus.gitee.io/zh-CN/component/form.html#%E8%A1%A8%E5%8D%95%E6%A0%A1%E9%AA%8C
      rules: { // 登录表单验证规则
        username: [
          {required: true, message: "请输入用户名", trigger: "blur"},
        ],
        password: [
          {required: true, message: "请输入密码", trigger: "blur"},
        ],
      },
      regRules: { // 注册表单验证规则
        name: [
          {required: true, message: "请填写姓名"},
        ],
        phone: [
          {
            required: true, message: "请填正确的手机号码", validator: (rule, value) => {
              return /1\d{10}/.test(value);
            }
          },
        ],
        password: [
          {required: true, message: "请填写登录密码"},
        ],
        identityNumber: [
          {
            required: true, message: "请填正确的身份证号", validator: (rule, value) => {
              return isCard(value);
            }
          }
        ],
      },
    }
  },
  setup() {
    const route = useRoute(); // 当前路由信息
    const loginHandle = useUserLogin();
    const param = reactive({
      username: "admin",
      password: "admin",
    });
    const role = ref(RoleTypes.doctor); // 登录角色
    const login = ref(null); // 指定登录表单的ref （相当于html的id固定写法）
    const submitForm = () => {
      loginHandle.login(param.username, param.password, role.value)
    };

    const store = useStore();
    store.commit("clearTags");


    const formRefName = ref(null); // 指定注册表单的ref （相当于html的id固定写法）
    const regData = reactive({
      show: isTrue(route.query.reg), // 如果存在路由参数reg则开启登录框，否则默认不开启
      data: {
        name: "",
        phone: "",
        department: "", // 部门（医生有）
        identityNumber: "", // 身份证号
        role: RoleTypes.doctor, // 角色 医生doctor、患者patient
        password: "",
        rePassword: "",
      }
    });
    const _regData = deepClone(toRaw(regData));

    /**
     * 打开关闭注册弹框
     * @param show {boolean} 打开状态
     * @returns {Promise<void>}
     */
    function toggleRegModal(show) {
      regData.show = show;
      // 设置默认值
      regData.data = Object.assign({}, _regData.data);

    }

    // 医生、患者注册
    function onRegister() {
      if (!formRefName.value) {
        Toast.error('找不到表单')
        return;
      }
      formRefName.value.validate(async (valid) => {
        if (!valid) { // 表单验证不通过
          return;
        }
        // 拷贝一份表单数据
        const _formData = deepClone(toRaw(regData)).data;
        try {
          let res = {}
          if (_formData.role === RoleTypes.doctor) { // 医生注册
            res = await Doctor.create(_formData)
          } else { // 患者注册
            res = await Patient.create(_formData);
          }
          Toast.success(res.message || '注册成功');
          toggleRegModal(false); //关闭注册弹框
        } catch (e) { // 注册操作提交错误或者失败
          Toast.error(e.message);
        }

      })
    }

    return {
      toggleRegModal,
      onRegister,
      formRefName,
      regData,
      role,
      param,
      login,
      submitForm,
    };
  },
};
</script>

<style scoped>
.login-wrap {
  position: relative;
  width: 100%;
  height: 100%;
  background-image: url(../assets/img/login-bg.jpg);
  background-size: 100%;
}

.ms-title {
  width: 100%;
  line-height: 50px;
  text-align: center;
  font-size: 20px;
  /*color: #fff;*/
  border-bottom: 1px solid #ddd;
}

.ms-login {
  position: absolute;
  left: 50%;
  top: 50%;
  width: 350px;
  margin: -190px 0 0 -175px;
  border-radius: 5px;
  background: rgba(255, 255, 255, 0.9);
  overflow: hidden;
}

.ms-content {
  padding: 30px 30px;
}

.login-btn {
  text-align: center;
}

.login-btn button {
  width: 100%;
  height: 36px;
  margin-bottom: 10px;
}

</style>
